import React, { useLayoutEffect, useMemo, useRef, useState } from "react";
import { DatePicker } from "antd";
import { useFormField } from "../../context/form-context";
import moment from "moment";
import locale from "antd/es/date-picker/locale/zh_CN";
import jQuery from "jquery";
import usePlacement from "../../lifecycle/usePlacement";
import useComponentWidth from "../../lifecycle/useComponentWidth";
import { getDatePicker, getIeHack, isIE } from "../../utils";
import set from "lodash/set"

let defaultConfig = {
  //这一批属性来源 tplData.form.data_control （步骤权限）
  // "code": "riqi",
  // "name": "日期",
  // "type": "date",
  // "is_show": true,
  // "is_editable": true,
  // "is_required": false,

  //这一批属性来源 tplData.form.form_meta_data （表单设计器）
  // "designProps": {
  //   "code": "riqi",
  //   "name": "日期",
  //   "ui": "wfd_datepicker",
  //   "title": "日期",
  //   "layout": "control_layout_leftRight",
  //   "defaultValue": "",
  //   "groupTitle": "",
  //   "byTableGroupTitle": false,
  //   "begin": "",
  //   "end": "",
  //   "format": "",
  //   "system": false,
  //   "text": "请选择日期",
  //   "tipstext": "",
  //   "type": "date",
  //   "title_w": 85
  // },
  // "isUsed": false,

  //这一批属性来源 tplData.form.data_define （业务对象）
  // "show_type": "",
  // "show_type_name": "",
  "props": {
       "format": "yyyy-mm-dd",//日期格式
  //     "source_type": "fixd_value",//默认值类型
  //     "configs": "default_date",//默认值
  //     "default_value": ""
  },
  // "type_name": " 日期",

  //来源 tplData.form.defaultValueConf
  // "default": null
}

export default function ({ field, label, rules, showLabel = false, onChange, displayFormatter, valueFormatter, required, cell, rowIndex, ...others }) {
  
  if(cell?.props?.format === undefined){//日期不存在格式化配置时，手动给默认的日期格式配置
    set(cell, "props.format", defaultConfig.props.format);
  }
  
  const { input, property, readonly, className, isDisplay } = useFormField({
    field,
    rules,
    onChange,
    displayFormatter,
    valueFormatter,
    triggerBlurAsChange: true,
  });

  const wrapperRef = useRef();

  let width=useComponentWidth(wrapperRef)

  let placemnet= usePlacement(wrapperRef)

  let value = input.value;

  //API给的format数据都是小写格式，需要转换成需要的正常格式
  let format = cell?.props?.format || "YYYY-MM-DD"; //配置的日期格式化
  format = format.replace("yyyy-mm", "YYYY-MM").replace("dd", "DD").replace("hh", "HH"); //转大写
  if (value == "current_date") {
    //当前时间
    input.onChange(moment(Date.now()).format(format));
  }
  else if(value===null ||value===undefined) //如果是null，表示没填时间，不需要格式化
  {

  } 
  else
  {
    //后端给的日期没有format，需要前端format后回填
    let newValue= moment(value).format(format);
    if(newValue=="Invalid date"){
      input.onChange(null,undefined,{isSilence:true});
    }
    else if(newValue!=value && newValue!=="Invalid date"){
      input.onChange(newValue);
    }
  }
  
  if (input.value && input.value._d == undefined) {
    value = moment(input.value);
  }

  if (isDisplay) {
    if (!value) {
      return null;
    }

    if (value == "default_date") {
      return null;
    }
    let formatValue = value?.format(format);
    return formatValue;
  }

  //根据format返回React日期组件需要的属性
  let [picker, showTime] = getDatePicker({format: cell?.props?.format});

  let component = useMemo(
    () => (
      <DatePicker
        allowClear={false}
        locale={locale}
        className={className}
        style={{width:"100%"}}
        placeholder={cell?.designProps?.text ? cell?.designProps?.text : "请选择"}
        format={format}
        picker={picker}
        showTime={showTime}
        // placement={"bottomLeft"}
        {...input}
        value={value}
        disabled={property.disabled}
        {...others}
        {...readonly}
        {...getIeHack()}
        placemnet={placemnet}
      ></DatePicker>
    ),
    [value, property.disabled, className, field, cell?.props?.format]
  );

  return <div ref={wrapperRef} style={{ maxWidth: width }}>{component}</div>
}
